package org.springboot.demo.config;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springboot.demo.entity.Teacher;
import org.springboot.demo.service.TeacherDaoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Configuration
public class MyRealms extends AuthorizingRealm {
    @Override
    public String getName() {
        return "myRealm";
    }
    @Autowired
    private TeacherDaoService teacherDaoService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //授权
//      Teacher teacher= (Teacher) principalCollection.getPrimaryPrincipal();
//        List<String> roles = new ArrayList<String>();
//        Set<String> permissions = new HashSet<String>();
//        for(Userrole role:teacher.getUserroleList()){
//            roles.add(role.getRoleList().getR_Name());
//            for(Rolepower permission:role.getRoleList().getPowerList()){
//                permissions.add(permission.getPower().getPermission());
//            }
//
//        }
//        SimpleAuthorizationInfo simpleAuthorizationInfo
//                = new SimpleAuthorizationInfo();
//        simpleAuthorizationInfo.addRoles(roles);
//        simpleAuthorizationInfo.addStringPermissions(permissions);
//        return simpleAuthorizationInfo;

        return  null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取登陆用户名
        String  loginName= (String) authenticationToken.getPrincipal();
        System.out.println(authenticationToken.getCredentials().toString());
        //查询
        Teacher teacher1=teacherDaoService.getByEntity(loginName);
        System.out.println(teacher1.getT_Password());
        if(teacher1==null){
                return null;
        }

        return new SimpleAuthenticationInfo(teacher1,teacher1.getT_Password(), ByteSource.Util.bytes(teacher1.getT_Salt()),getName());
    }
}
